﻿package nieAS.net {
	import flash.events.AsyncErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.external.ExternalInterface;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.net.NetStreamInfo;
	import flash.utils.setTimeout;
	
	public class NieNetStream extends NetStream {
		private var stats:NieStats = new NieStats();
		private var has_stats:Boolean = false;
		private var _timer = null;
		private const _time = 60 * 1000; //一分钟统计数据	
		private var _netStatusTimes:uint = 0; //网络状态变化次数
		
		public function NieNetStream(conn:NetConnection, peerID:String = "connectToFMS") {
			super(conn, peerID);
			addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			addEventListener(AsyncErrorEvent.ASYNC_ERROR, netAsyncErrorHandler);
			addEventListener(IOErrorEvent.NETWORK_ERROR, stream_error);
		}
		
		public function set videodatarate(val):void {
			stats.vbr = val;
		}
		
		private function netStatusHandler(evt:NetStatusEvent):void {
			++_netStatusTimes;
			stats.pushEvtLog(evt.info.code);
			//http://livedocs.adobe.com/flex/3_cn/langref/flash/events/NetStatusEvent.html
			if (evt.info.level == "error") {
				stats.play_error();
			}
			switch (evt.info.code) {
				//播放已结束。
				case "NetStream.Play.Stop": 
					if (_netStatusTimes > 1) {
						stats.play_finish();
						sendData();
					}
					break;
				//数据的接收速度不足以填充缓冲区。 数据流将在缓冲区重新填充前中断，此时将发送 NetStream.Buffer.Full 消息，并且该流将重新开始播放。
				case "NetStream.Buffer.Empty": 
					stats.start_buffer();
					break;
				//缓冲区已满并且流将开始播放。
				case "NetStream.Buffer.Full": 
					stats.end_buffer();
					break;
				//播放已开始。
				case "NetStream.Play.Start": 
					stats.start_buffer();
					break;
			}
		}
		
		private function netAsyncErrorHandler(evt:AsyncErrorEvent):void {
			stats.play_error();
		}
		
		private function stream_error(evt:IOErrorEvent):void {
			stats.play_error();
		}
		
		private function sendData():void {
			if (!has_stats) {
				has_stats = true;
				stats.send_data();
			}
		}
		
		override public function play(... args):void {
			super.play(args[0]);
			if (args.length > 0) {
				if ((args[0] as String).indexOf("http://") != -1) {
					stats.movieUrl = args[0];
					_timer = setTimeout(sendData, _time);
				}
			}
		}
	}

}